/**
 *
 */
package gemini.basic.dao.impl;

import gemini.basic.dao.CustomerDao;
import gemini.basic.dao.GmnDao;
import gemini.basic.model.AbstractDomain;
import gemini.basic.model.Customer;
import gemini.basic.model.Event;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 *
 *
 */
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {

	private GmnDao gmnDao;

	public void setGmnDao(GmnDao gmnDao) {
		this.gmnDao = gmnDao;
	}

	@Override
	public Customer saveOrUpdate(Customer customer, boolean flush) {
		Customer result = null;
		if (flush) {
			result = (Customer) gmnDao.saveOrUpdateAndFlush(customer);
		} else {
			result = (Customer) gmnDao.saveOrUpdate(customer);
		}
		return result;
	}

	@Override
	public List<Customer> getCustomerByDistributorCode(String code) {
		DetachedCriteria dtCri = DetachedCriteria.forClass(Customer.class);
		dtCri.createAlias("distributor", "dis");

		dtCri.add(Restrictions.eq("dis.code", code));

		List<Object> customerList = gmnDao.findByCriteria(dtCri);

		List<Customer> result = null;

		if (customerList != null && !customerList.isEmpty()) {
			result = new ArrayList<Customer>(customerList.size());
			Customer customer = null;
			for (Object ob : customerList) {
				customer = (Customer) ob;
				result.add(customer);
			}
		}

		return result;
	}
	
	@Override
	public Customer getById(int id) {
		DetachedCriteria dtCri = DetachedCriteria.forClass(Customer.class);

		if (id != AbstractDomain.TRANSIENT_ENTITY_ID) {
			dtCri.add(Restrictions.eq("id", id));
		}

		List<Object> resultList = gmnDao.findByCriteria(dtCri);

		Customer result = null;
		
		if (resultList != null && !resultList.isEmpty()) {
			result = (Customer) resultList.get(0);
		}
		return result;
	}

	@Override
	public void deleteCustomer(Customer customer) {
		getHibernateTemplate().delete(customer);
	}

}
